#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <unistd.h>
using namespace std;

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

class UdpServer{
public:
    UdpServer(const uint16_t &port = defaultport, 
    const std::string &ip = defaultip):sockfd_(0), port_(port), ip_(ip)
    {}
    void Init()
    {
        // 1. 创建udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); 
        printf("socket create success, sockfd: %d\n", sockfd_);
        // 2. bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_); 
        local.sin_addr.s_addr = inet_addr(ip_.c_str()); 

        bind(sockfd_, (const struct sockaddr *)&local, sizeof(local));
        printf("bind success, errno: %d, \
        err string: %s\n", errno, strerror(errno));
    }
    void Run() // 对代码进行分层
    {
        while(true)
        {
        char inbuffer[size];
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            //服务器先接收消息
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1,
             0, (struct sockaddr*)&client, &len);
            inbuffer[n] = 0;
            cout<<"客户端说:"<<inbuffer<<endl;
            std::string info = inbuffer;
            std::string echo_string = "服务器的回答："+info;
            //再反馈消息
            sendto(sockfd_, echo_string.c_str(), echo_string.size()
            , 0, (const sockaddr*)&client, len);
        }
    }
    ~UdpServer()
    {
        if(sockfd_>0) close(sockfd_);//关闭描述符
    }
private:
    int sockfd_;     // 网路文件描述符
    std::string ip_; // ip地址
    uint16_t port_;  // 服务器端口号
};